// index.js

Page({
  data: {
    showTip: false,
    isSpeaking: false
  },
  recMsgr: null,
  access_token: '24.cb33f17ad174bd75512af03a4dc3a572.2592000.1602929609.282335-22683560',
  onLoad: function () {
    this.recMsgr = wx.getRecorderManager()
    this.recMsgr.onStop((res) => {
      this.recIdentify(res.tempFilePath)
    })
  },
  onShow: function () {
    var showTip = wx.getStorageSync("showTip");
    if (showTip) {
      this.setData({
        showTip: true
      })
      setTimeout(() => {
        this.setData({
          showTip: false
        })
        wx.setStorageSync("showTip", false)
      }, 3000)
    }
  },
  goSearch: function (value) {
    wx.navigateTo({
      url: '/pages/ai/search/search?searchText=' + value
    })
  },
  goCamera: function () {
    wx.navigateTo({
      url: '/pages/ai/camera/camera',
    });
  },
  startREC() {
    this.speaking()
    this.setData({
      isSpeaking: true
    })
    this.recMsgr.start({
      sampleRate: 16000,
      format: 'PCM'
    })
  },
  endREC() {
    clearInterval(this.timer);
    this.setData({
      isSpeaking: false
    })
    this.recMsgr.stop()
  },
  recIdentify(filePath) {
    wx.showLoading({
      title: '正在识别',
    })
    wx.request({
      url: 'https://vop.baidu.com/pro_api?cuid=1&dev_pid=80001&token=' + this.access_token,
      data: {
        raw: wx.getFileSystemManager().readFileSync(filePath, 'binary')
      },
      header: {
        'content-type': 'audio/pcm;rate=16000'
      },
      method: 'POST',
      success: (res) => {
        if (!res.err_no) {
          var result = res.data.result[0]
          result = result.replace(/[\ |\，|\。|\？]/g, "")
          this.goSearch(result)
        } else {
          console.log(res.data.error_msg);
        }
      },
      fail: (res) => {
        console.log(res);
      },
      complete: (res) => {
        console.log(JSON.stringify(res));
        wx.hideLoading({
          success: (res) => { },
        })
      }
    })
  },
  //话筒帧动画
  speaking: function () {
    var _this = this
    var i = 1;
    this.timer = setInterval(function () {
      i++;
      i = i % 5;
      _this.setData({
        i: i
      })
    }, 200);
  }
});
